package com.zrfintech.manage.aop;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.zrfintech.manage.util.HttpResponseUtil;
import com.zrfintech.manage.util.RequestContextUtil;
import com.zrfintech.manage.vo.HttpResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class UserLoginInterceptor implements HandlerInterceptor {

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String userCode = request.getHeader("user_code");
            if (Strings.isNullOrEmpty(userCode) || "null".equals(userCode)) {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                HttpResponse httpResponse = HttpResponseUtil.loginError();
                writer.write(new ObjectMapper().writeValueAsString(httpResponse));
                writer.flush();
                writer.close();
                return false;
            }
            RequestContextUtil.setRealUser(userCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}


